package ecoll.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.RootPanel;

import ecoll.client.centers.NewsCenter;
import ecoll.client.login.LoginInfo;
import ecoll.client.widgets.LoginPanel;
import ecoll.client.widgets.MainMenu;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class EldilCenterOfLanguageLearning implements EntryPoint {

	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.";
	private static final String WELCOME_IMAGE = "http://farm3.staticflickr.com/2544/3809460658_3d36d44eaa.jpg";
	private static final String WI_WIDTH = "420px";
	private static final String WI_HEIGHT = "400px";

	private LoginPanel loginPanel = new LoginPanel(true);

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		RootPanel.get().setStyleName("body");
		RootPanel.get("mainPanel").add(Client.mainPanel);

		Client.LOGIN_SERVICE.login(GWT.getHostPageBaseURL(),
				new AsyncCallback<LoginInfo>() {
					public void onFailure(Throwable error) {
						Window.alert("Login failure");
					}

					public void onSuccess(LoginInfo result) {

						Client.LOGIN_INFO = result;

						if (result.isLoggedIn()) {

							Client.DATABASE_SERVICE.putNews("Logged in",
									new AsyncCallback<Void>() {

										@Override
										public void onFailure(Throwable e) {
											Window.alert("Failure while processing login information: "
													+ e.getMessage());
										}

										@Override
										public void onSuccess(Void result) {
											createMainPage();
										}
									});

						} else {
							createWelcomePage();
						}
					}
				});
	}

	private void createWelcomePage() {
		RootPanel.get("loginPanel").add(loginPanel);
		loginPanel.enableLogin(Client.LOGIN_INFO.getLoginUrl());

		Image welcomeImage = new Image(WELCOME_IMAGE);
		welcomeImage.setSize(WI_WIDTH, WI_HEIGHT);
		welcomeImage.setStyleName("welcomeImage");
		Client.mainPanel.add(welcomeImage, DockPanel.CENTER);
	}

	private void createMainPage() {
		RootPanel.get("loginPanel").add(loginPanel);
		loginPanel.enableLogout(Client.LOGIN_INFO.getNickname(),
				Client.LOGIN_INFO.getLogoutUrl());

		Client.resetDashboard();
		new NewsCenter().execute();
		MainMenu mainMenu = new MainMenu();
		mainMenu.setStyleName("mainMenu");
		Client.mainPanel.add(mainMenu, DockPanel.WEST);
	}

}
